package com.lx.chong.utils.pageable;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.List;

/**
 * 构造 pageable 工具类
 *
 * @author: whh
 * @date: 2017/12/18
 */
public class PageableUtil {

    public static PageRequest buildPageRequest(MyPage page, List<MySort> sorts) {
        List<Sort.Order> sortOrderList = new ArrayList<>();
        for (MySort sort : sorts) {
            String type = sort.getDir();
            // 默认使用倒叙
            Sort.Direction direction = Sort.Direction.DESC;
            if ("asc".equalsIgnoreCase(type)) {
                direction = Sort.Direction.ASC;
            }
            Sort.Order order = new Sort.Order(direction, sort.getProp());
            sortOrderList.add(order);
        }
        if (page == null || page.getPageNum() == null || page.getPageSize() == null) {
            return null;
        }
        if (sortOrderList.size() == 0) {
            return new PageRequest(page.getPageNum() - 1, page.getPageSize());
        }
        return new PageRequest(page.getPageNum() - 1, page.getPageSize(), new Sort(sortOrderList));
    }

}
